/**
 * 抽屉管理器类
 * 用于管理主机连接、常用目录和备忘录功能
 */
class DrawerManager {
    constructor() {
        this.layer = null;
        this.form = null;
        this.$ = null;
        this.drawerIndex = null; // 存储抽屉的layer索引
        this.eventsInitialized = false; // 标记事件是否已初始化
        
        // 数据存储
        // this.hosts = JSON.parse(localStorage.getItem('hosts') || '[]');
        // this.directories = JSON.parse(localStorage.getItem('directories') || '[]');
        // this.currentHost = localStorage.getItem('currentHost') || '未连接';
        // this.currentHostIP = localStorage.getItem('currentHostIP') || '';
        // this.currentHostPort = localStorage.getItem('currentHostPort') || '';
        // this.currentUsername = localStorage.getItem('currentUsername') || '';
        // this.currentPassword = localStorage.getItem('currentPassword') || '';
        // this.currentPath = localStorage.getItem('currentPath') || '';
        // this.maxDepth = localStorage.getItem('maxDepth') || 3;


        // this.hosts = JSON.parse(localStorage.getItem('hosts') || '[]');
        // this.directories = JSON.parse(localStorage.getItem('directories') || '[]');
        // this.memo = localStorage.getItem('memo') || '';


        this.hosts = [];  
        this.directories = [];  
        this.memo = "";

        this.currentHost = '未连接';
        this.currentHostIP = '';
        this.currentHostPort = '';
        this.currentUsername = '';
        this.currentPassword = '';
        this.currentPath = '';
        this.currentMaxDepth = 1;


        // 配置管理相关
        this.currentConfigName = '默认配置'; // 当前配置名称
        this.availableConfigs = []; // 后端可用的配置列表

        
        this.init();
    }

    /**
     * 初始化
     */
    init() {
        const self = this;
        layui.use(['layer', 'form'], function(){
            self.layer = layui.layer;
            self.form = layui.form;
            self.$ = layui.$;
            self.upload = layui.upload;

            self.initDefaultData();
            self.bindTriggerEvent();
            self.loadAvailableConfigs(); // 加载后端可用配置

            // 如果存在SocketClient，绑定配置管理相关的事件监听
            if (window.SocketClient && window.SocketClient.socket) {
                // 监听配置列表返回
                window.SocketClient.socket.on('config_list', function(data) {
                    window.DrawerManager.handleConfigListResponse(data);
                    
                });

                // 监听配置保存结果
                window.SocketClient.socket.on('config_saved', function(data) {
                    window.DrawerManager.handleConfigSaved(data);
                });

                // 监听配置加载结果
                window.SocketClient.socket.on('config_loaded', function(data) {
                    window.DrawerManager.handleConfigLoaded(data);
                });

                // 监听配置删除结果
                window.SocketClient.socket.on('config_deleted', function(data) {
                    window.DrawerManager.handleConfigDeleted(data);
                });
            }

        });
    }

    /**
     * 初始化默认数据
     */
    initDefaultData() {
        if (this.hosts.length === 0) {
            this.hosts = [
                {
                    name: '开发服务器',
                    ip: '192.168.1.100',
                    port: '22',
                    username: 'developer',
                    password: '******',
                    path: '/var/www',
                    maxDepth: 3
                },
                {
                    name: '生产服务器',
                    ip: '10.0.0.50',
                    port: '2222',
                    username: 'admin',
                    password: '******',
                    path: '/home/admin',
                    maxDepth: 3
                }
            ];
        }

        if (this.directories.length === 0) {
            this.directories = [
                {alias: '项目根目录', path: '/var/www/project'},
                {alias: '日志目录', path: '/var/log/nginx'},
                {alias: '配置目录', path: '/etc/nginx'}
            ];
        }

        if (!this.memo) {
            this.memo = '这里可以记录一些临时内容...\n\n例如：\n- 待处理的任务\n- 重要的命令\n- 临时笔记';
        }

        this.saveData();
    }

    /**
     * 绑定触发按钮事件
     */
    bindTriggerEvent() {
        const self = this;
        document.getElementById('drawerBtn').onclick = function() {
            self.openDrawer();
        };
    }

     /**
     * 与后端通信 - 加载可用配置列表
     */
    loadAvailableConfigs() {
        if (window.SocketClient && window.SocketClient.socket) {
            this.layer.msg('正在加载配置列表...', {icon: 16, time: 2000});

            window.SocketClient.socket.emit('load_config_list',[]);
        }
    }


     /**
     * 与后端通信 - 保存配置到后端
     */
    saveConfigToBackend(configName) {
        if (!configName || configName.trim() === '') {
            this.layer.msg('配置名称不能为空', {icon: 2});
            return;
        }

        const configData = {
            name: configName,
            hosts: this.hosts,
            directories: this.directories,
            memo: this.memo
        };

        if (window.SocketClient && window.SocketClient.socket) {
            window.SocketClient.socket.emit('save_config', configData);
            this.currentConfigName = configName;
            this.updateCurrentConfigDisplay();
        } else {
            this.layer.msg('未连接到后端服务', {icon: 2});
        }
    }


    /**
     * 与后端通信 - 加载指定配置
     */
    loadConfigFromBackend(configName) {
        if (window.SocketClient && window.SocketClient.socket) {
            this.layer.msg('正在加载配置... '+configName, {icon: 16, time: 2000});

            window.SocketClient.socket.emit('load_config', configName);
        }
    }


     /**
     * 应用从后端加载的配置数据
     */
    applyLoadedConfig(configData) {
        this.hosts = configData.hosts || [];
        this.directories = configData.directories || [];
        this.memo = configData.memo || '';
        this.currentConfigName = configData.name || '未知配置';

        // 更新显示
        if (this.drawerIndex) {
            this.initDrawerContent();
            this.form.render();
        }

        this.layer.msg(`配置 "${this.currentConfigName}" 加载成功`, {icon: 1});
    }


     /**
     * 下载配置到本地
     */
    downloadConfig() {
        // 获取日期时间
        var timestamp = new Date().toLocaleString();

        const configData = {
            name: this.currentConfigName,
            timestamp: timestamp,
            hosts: this.hosts,
            directories: this.directories,
            memo: this.memo            
        };

        const dataStr = JSON.stringify(configData, null, 2);
        const dataBlob = new Blob([dataStr], {type: 'application/json'});
        
        const link = document.createElement('a');
        link.href = URL.createObjectURL(dataBlob);
        link.download = `${this.currentConfigName}_${timestamp}.json`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.layer.msg('配置文件已下载', {icon: 1});
    }

    /**
     * 从本地文件加载配置
     */
    loadConfigFromFile(fileContent) {
        try {
            const configData = JSON.parse(fileContent);

            console.log(configData);
            
            // 验证配置文件格式
            if (!configData.hosts || !Array.isArray(configData.hosts)) {
                throw new Error('配置文件格式错误：缺少主机配置');
            }
            
            if (!configData.directories || !Array.isArray(configData.directories)) {
                throw new Error('配置文件格式错误：缺少目录配置');
            }

            // 应用配置
            this.applyLoadedConfig(configData);
            
        } catch (error) {
            this.layer.msg('配置文件解析失败：' + error.message, {icon: 2});
        }
    }

    /**
     * 更新当前配置名称显示
     */
    updateCurrentConfigDisplay() {
        if (this.$('#currentConfigName').length) {
            this.$('#currentConfigName').text(this.currentConfigName);
        }
    }


    /**
     * 保存数据到本地存储
     */
    saveData() {
        localStorage.setItem('hosts', JSON.stringify(this.hosts));
        localStorage.setItem('directories', JSON.stringify(this.directories));
        localStorage.setItem('currentHost', this.currentHost);
        localStorage.setItem('currentHostIP', this.currentHostIP);
        localStorage.setItem('currentHostPort', this.currentHostPort);
        localStorage.setItem('currentUsername', this.currentUsername);
        localStorage.setItem('currentPassword', this.currentPassword);
        localStorage.setItem('currentPath', this.currentPath);
        localStorage.setItem('maxDepth', this.maxDepth);
        localStorage.setItem('memo', this.memo);
    }

    /**
     * 获取抽屉HTML内容
     */
    getDrawerContent() {
        return `
        <div class="drawer-content">
            <!-- 配置管理 -->
            <div class="section-card">
                <div class="section-title">
                    <i class="layui-icon layui-icon-set"></i> 配置管理
                </div>
                <div class="current-config">
                    <strong>当前配置：</strong> <span id="currentConfigName">${this.currentConfigName}</span>
                </div>
                <div style="margin: 10px;">
                    <div class="layui-btn-group">
                        <button class="layui-btn layui-btn-sm layui-btn-normal" id="uploadConfigBtn">加载本地配置</button>
                        <button class="layui-btn layui-btn-sm layui-btn-warm" id="downloadConfigBtn">下载当前配置</button>
                        <button class="layui-btn layui-btn-sm" id="refreshConfigBtn">拉取后端列表</button>

                        <button class="layui-btn layui-btn-sm" id="saveConfigBtn">保存到后端</button>
                    </div>
                    <input type="file" id="configFileInput" accept=".json" style="display: none;">
                </div>
                <div id="configList"></div>
            </div>

            <!-- 主机管理 -->
            <div class="section-card">
                <div class="section-title">
                    <i class="layui-icon layui-icon-service"></i> 主机管理
                </div>
                <div class="current-host">
                    <strong>当前主机：</strong> <span id="currentHostName">${this.currentHost}</span>
                    <strong>IP: </strong> <span id="currentHostIP">${this.currentHostIP}</span>
                    <strong>端口: </strong> <span id="currentHostPort">${this.currentHostPort}</span>
                    <strong>用户名: </strong> <span id="currentUsername">${this.currentUsername}</span>
                    <strong>路径: </strong> <span id="currentPath">${this.currentPath}</span>
                    <strong>最大深度: </strong> <span id="currentMaxDepth">${this.currentMaxDepth}</span>
                </div>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="addHost">
                    <i class="layui-icon layui-icon-add-1"></i> 添加主机
                </button>
                <div id="hostList"></div>
            </div>

            <!-- 常用目录 -->
            <div class="section-card">
                <div class="section-title">
                    <i class="layui-icon layui-icon-file"></i> 常用目录
                </div>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="addDir">
                    <i class="layui-icon layui-icon-add-1"></i> 添加目录
                </button>
                <div id="dirList"></div>
            </div>

            <!-- 备忘录 -->
            <div class="section-card">
                <div class="section-title">
                    <i class="layui-icon layui-icon-note"></i> 备忘录
                </div>
                <textarea class="layui-textarea memo-textarea" id="memoText" placeholder="在此记录临时内容...">${this.memo}</textarea>
                <button type="button" class="layui-btn layui-btn-sm" id="saveMemo" style="margin-top: 10px;">
                    <i class="layui-icon layui-icon-ok"></i> 保存备忘
                </button>
            </div>
        </div>
        `;
    }

    /**
     * 打开抽屉
     */
    openDrawer() {
        const self = this;
        this.drawerIndex = this.layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            area: ['800px', '100%'],
            shade: 0.3,
            shadeClose: true,
            offset: 'r',
            anim: 'slideLeft',
            content: this.getDrawerContent(),
            success: function(layero, index) {
                self.initDrawerContent();
                self.form.render();
                self.loadAvailableConfigs(); // 刷新配置列表
            }
        });
    }

    /**
     * 初始化抽屉内容
     */
    initDrawerContent() {
        this.renderConfigList();
        this.renderHostList();
        this.renderDirList();
         this.updateCurrentConfigDisplay();
        // 只在第一次初始化事件，避免重复绑定
        if (!this.eventsInitialized) {
            this.bindDrawerEvents();
            this.eventsInitialized = true;
        }
    }

    /**
     * 渲染配置列表
     */
    renderConfigList() {
        let html = '';
        if (this.availableConfigs.length > 0) {
            html += '<div style="margin-top: 10px;"><strong>后端配置列表：</strong></div>';
            this.availableConfigs.forEach((configName, index) => {
                html += `
                <div class="config-item" data-config-name="${configName}">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span style="flex: 1;">${configName}</span>
                        <div>
                            <button class="layui-btn layui-btn-xs layui-btn-normal load-config" 
                                    data-config="${configName}">加载</button>
                            <button class="layui-btn layui-btn-xs layui-btn-danger delete-config" 
                                    data-config="${configName}">删除</button>
                        </div>
                    </div>
                </div>
                `;
            });
        } else {
            html = '<div style="margin-top: 10px; color: #999;">暂无后端配置</div>';
        }
        this.$('#configList').html(html);
    }

    /**
     * 渲染主机列表
     */
    renderHostList() {
        let html = '';
        this.hosts.forEach((host, index) => {
            html += `
            <div class="host-item" data-index="${index}">
                <div style="margin-bottom: 8px;">
                    <strong>${host.name}</strong>
                    <span class="item-actions">
                        <button class="layui-btn layui-btn-xs layui-btn-normal apply-host">应用</button>
                        <button class="layui-btn layui-btn-xs test-host">测试</button>
                        <button class="layui-btn layui-btn-xs edit-host">编辑</button>
                        <button class="layui-btn layui-btn-xs layui-btn-danger delete-host">删除</button>
                    </span>
                </div>
                <div class="host-info">
                    <div>IP: ${host.ip}</div>
                    <div>端口: ${host.port}</div>
                    <div>用户: ${host.username}</div>
                    <div>路径: ${host.path}</div>
                    <div>最大深度: ${host.maxDepth}</div>
                </div>
            </div>
            `;
        });
        this.$('#hostList').html(html);
    }

    /**
     * 渲染目录列表
     */
    renderDirList() {
        let html = '';
        this.directories.forEach((dir, index) => {
            html += `
            <div class="dir-item" data-index="${index}">
                <div>
                    <strong>${dir.alias}</strong>
                    <span class="item-actions">
                        <button class="layui-btn layui-btn-xs layui-btn-normal jump-dir">跳转</button>
                        <button class="layui-btn layui-btn-xs edit-dir">编辑</button>
                        <button class="layui-btn layui-btn-xs layui-btn-danger delete-dir">删除</button>
                    </span>
                </div>
                <div style="font-size: 12px; color: #666; margin-top: 5px;">${dir.path}</div>
            </div>
            `;
        });
        this.$('#dirList').html(html);
    }

    /**
     * 绑定抽屉内事件
     */
    bindDrawerEvents() {
        const self = this;
        const $ = this.$;

         // 配置管理事件
        $(document).on('click', '#saveConfigBtn', function() {

            // const configName = $('#configNameInput').val().trim();
            // if (!configName) {
            //     self.layer.msg('请输入配置名称', {icon: 2});
            //     return;
            // }
            self.layer.prompt({
                title: '请输入保存名称',
                formType: 0,
                area: ['400px', '200px'],
            }, (value, index, elem) => {
                if(value === '') return elem.focus();
                self.layer.msg(`获取：${value}`, {icon: 1});
                self.saveConfigToBackend(value);
                self.layer.close(index);
            });
        });

        $(document).on('click', '#uploadConfigBtn', function() {
            $('#configFileInput').click();
        });

        $(document).on('change', '#configFileInput', function(e) {
            const file = e.target.files[0];
            if (file) {
                console.log(`获取：${file.name}`, {icon: 1});

                const reader = new FileReader();
                reader.onload = function(e) {
                    self.loadConfigFromFile(e.target.result);
                };
                reader.readAsText(file);
            }
        });

        $(document).on('click', '#downloadConfigBtn', function() {
            self.downloadConfig();
        });

        $(document).on('click', '#refreshConfigBtn', function() {
            self.loadAvailableConfigs();
        });

        $(document).on('click', '.load-config', function() {
            const configName = $(this).data('config');
            self.loadConfigFromBackend(configName);
        });

        $(document).on('click', '.delete-config', function() {
            const configName = $(this).data('config');
            self.layer.confirm(`确定删除配置 "${configName}"？`, function(confirmIndex) {
                if (window.SocketClient && window.SocketClient.socket) {
                    window.SocketClient.socket.emit('delete_config', configName);
                }
                self.layer.close(confirmIndex);
            });
        });


        // 主机管理事件
        $(document).on('click', '#addHost', () => this.showHostForm());
        $(document).on('click', '.edit-host', function() {
            const index = $(this).closest('.host-item').data('index');
            self.showHostForm(self.hosts[index], index);
        });
        $(document).on('click', '.delete-host', function() {
            const index = $(this).closest('.host-item').data('index');
            self.deleteHost(index);
        });
        $(document).on('click', '.apply-host', function() {
            const index = $(this).closest('.host-item').data('index');
            self.applyHost(index);
        });
        $(document).on('click', '.test-host', function() {
            const index = $(this).closest('.host-item').data('index');
            self.testConnection(index);
        });

        // 目录管理事件
        $(document).on('click', '#addDir', () => this.showDirForm());
        $(document).on('click', '.edit-dir', function() {
            const index = $(this).closest('.dir-item').data('index');
            self.showDirForm(self.directories[index], index);
        });
        $(document).on('click', '.delete-dir', function() {
            const index = $(this).closest('.dir-item').data('index');
            self.deleteDirectory(index);
        });
        $(document).on('click', '.jump-dir', function() {
            const index = $(this).closest('.dir-item').data('index');
            self.jumpToDirectory(index);
        });
        // 双击事件
        $(document).on('dblclick', '.host-item', function() {
            const index = $(this).data('index');
            self.applyHost(index);
        });
        $(document).on('dblclick', '.dir-item', function() {
            const index = $(this).data('index');
            self.jumpToDirectory(index);
        });

        // 配置管理事件
        $(document).on('dblclick', '.config-item', function() {
            const configName = $(this).data('configName');
            self.loadConfigFromBackend(configName);
        });


        // 备忘录事件
        $(document).on('click', '#saveMemo', () => this.saveMemo());
        $(document).on('input', '#memoText', function() {
            self.memo = $(this).val();
            self.saveData();
        });
    }

    /**
     * 显示主机表单
     */
    showHostForm(host, index) {
        const title = host ? '编辑主机' : '添加主机';
        const formData = host || {name: '', ip: '', port: '22', username: '', password: '', path: '/home', maxDepth: 3};

        const self = this;
        
        const formIndex = this.layer.open({
            type: 1,
            title: title,
            area: ['700px', 'auto'],
            content: `
            <form class="layui-form" style="padding: 20px;">
                <div class="form-row">
                    <label>主机名：</label>
                    <input type="text" name="name" value="${formData.name}" class="layui-input" required lay-verify="required">
                </div>
                <div class="form-row">
                    <label>IP地址：</label>
                    <input type="text" name="ip" value="${formData.ip}" class="layui-input" required lay-verify="required">
                </div>
                <div class="form-row">
                    <label>端口：</label>
                    <input type="text" name="port" value="${formData.port}" class="layui-input" required lay-verify="required">
                </div>
                <div class="form-row">
                    <label>用户名：</label>
                    <input type="text" name="username" value="${formData.username}" class="layui-input" required lay-verify="required">
                </div>
                <div class="form-row">
                    <label>密码：</label>
                    <input type="password" name="password" value="${formData.password}" class="layui-input" required lay-verify="required">
                </div>
                <div class="form-row">
                    <label>初始路径：</label>
                    <input type="text" name="path" value="${formData.path}" class="layui-input" required lay-verify="required">
                </div>
                <div class="form-row">
                    <label>最大深度：</label>
                    <input type="text" name="maxDepth" value="${formData.maxDepth}" class="layui-input" required lay-verify="required">
                </div>
                <div style="text-align: center; margin-top: 20px;">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="hostForm">确定</button>
                    <button type="button" class="layui-btn layui-btn-primary cancel-btn">取消</button>
                </div>
            </form>
            `,
            success: function(layero, currentIndex) {
                // 绑定取消按钮事件
                layero.find('.cancel-btn').on('click', function() {
                    self.layer.close(currentIndex);
                });

                self.form.on('submit(hostForm)', function(data) {
                    const hostData = data.field;
                    if (typeof index !== 'undefined') {
                        self.hosts[index] = hostData;
                    } else {
                        self.hosts.push(hostData);
                    }
                    self.saveData();
                    self.renderHostList();
                    self.layer.close(currentIndex);
                    self.layer.msg(title + '成功', {icon: 1});
                    return false;
                });
            }
        });
    }

    /**
     * 显示目录表单
     */
    showDirForm(dir, index) {
        const title = dir ? '编辑目录' : '添加目录';
        const formData = dir || {alias: '', path: ''};
        const self = this;
        
        const formIndex = this.layer.open({
            type: 1,
            title: title,
            area: ['700px', 'auto'],
            content: `
            <form class="layui-form" style="padding: 20px;">
                <div class="form-row">
                    <label>别称：</label>
                    <input type="text" name="alias" value="${formData.alias}" class="layui-input" required lay-verify="required" placeholder="给目录起个好听的名字">
                </div>
                <div class="form-row">
                    <label>路径：</label>
                    <input type="text" name="path" value="${formData.path}" class="layui-input" required lay-verify="required" placeholder="/home/user/documents">
                </div>
                <div style="text-align: center; margin-top: 20px;">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="dirForm">确定</button>
                    <button type="button" class="layui-btn layui-btn-primary cancel-btn">取消</button>
                </div>
            </form>
            `,
            success: function(layero, currentIndex) {
                // 绑定取消按钮事件
                layero.find('.cancel-btn').on('click', function() {
                    self.layer.close(currentIndex);
                });

                self.form.on('submit(dirForm)', function(data) {
                    const dirData = data.field;
                    if (typeof index !== 'undefined') {
                        self.directories[index] = dirData;
                    } else {
                        self.directories.push(dirData);
                    }
                    self.saveData();
                    self.renderDirList();
                    self.layer.close(currentIndex);
                    self.layer.msg(title + '成功', {icon: 1});
                    return false;
                });
            }
        });
    }

    /**
     * 删除主机
     */
    deleteHost(index) {
        const self = this;
        this.layer.confirm('确定删除此主机配置？', function(confirmIndex) {
            self.hosts.splice(index, 1);
            self.saveData();
            self.renderHostList();
            self.layer.close(confirmIndex);
        });
    }

    /**
     * 应用主机
     */
    applyHost(index) {
        this.currentHost = this.hosts[index].name;
        this.currentHostIP = this.hosts[index].ip;
        this.currentHostPort = this.hosts[index].port;
        this.currentUsername = this.hosts[index].username;
        this.currentPassword = this.hosts[index].password;
        this.currentPath = this.hosts[index].path;
        this.currentMaxDepth = this.hosts[index].maxDepth;


        this.$('#currentHostName').text(this.currentHost);
        this.$('#currentHostIP').text(this.currentHostIP);
        this.$('#currentHostPort').text(this.currentHostPort);
        this.$('#currentUsername').text(this.currentUsername);
        this.$('#currentPassword').text(this.currentPassword);
        this.$('#currentPath').text(this.currentPath);
        this.$('#currentMaxDepth').text(this.currentMaxDepth);

        this.saveData();
        


        console.log('加载目录');
        const config = this.getCurrentConfig();

        if (!config || !config.name) {
            return;
        }
        if (window.SocketClient) {
            window.SocketClient.loginRemote(config);
        }
        if (window.TreeManager) {
            window.TreeManager.loadTree();
        }
        if (window.DetailManager) {
            window.DetailManager.loadDirectory();
        }

        // this.layer.msg('已应用主机：' + this.currentHost);

    }

    /**
     * 测试连接
     */
    testConnection(index) {
        const host = this.hosts[index];
        this.layer.msg('正在测试连接...', {icon: 16, time: 10000});

        const config = {
            name: host.name,
            host: host.ip,
            port: host.port,
            username: host.username,
            password: host.password,
            remotePath: host.path,
            maxDepth: host.maxDepth
        }
        if (window.SocketClient) {
            window.SocketClient.loginRemote(config);
        }
    }

    /**
     * 删除目录
     */
    deleteDirectory(index) {
        const self = this;
        this.layer.confirm('确定删除此目录跳转？', function(confirmIndex) {
            self.directories.splice(index, 1);
            self.saveData();
            self.renderDirList();
            self.layer.close(confirmIndex);
        });
    }

    /**
     * 跳转目录
     */
    jumpToDirectory(index) {
        const dir = this.directories[index];
        // this.layer.msg('跳转到：' + dir.path, {icon: 1});

        if (window.DetailManager) {
            window.DetailManager.getFileListByPath(dir.path);
        }
        if (window.TreeManager) {
            window.TreeManager.loadTreeWithPath(dir.path);
        }

    }

    /**
     * 保存备忘录
     */
    saveMemo() {
        this.memo = this.$('#memoText').val();
        this.saveData();
        this.layer.msg('备忘录已保存', {icon: 1});
    }

    // 获取当前配置
    getCurrentConfig() {
        const name = this.currentHost;
        const host = this.currentHostIP;
        const port = this.currentHostPort;
        const username = this.currentUsername;
        const password = this.currentPassword;
        const remotePath = this.currentPath;
        const maxDepth = this.currentMaxDepth;
        const config = {
            name,
            host,
            port,
            username,
            password,
            remotePath,
            maxDepth
        }
        return config;
    }



    /**
     * 处理后端返回的配置列表
     */
    handleConfigListResponse(configList) {
        this.availableConfigs = configList || [];
        if (this.drawerIndex) {
            this.renderConfigList();
        }
        this.layer.msg('加载配置列表成功', {icon: 1, time: 800});
    }

    /**
     * 处理配置保存成功回调
     */
    handleConfigSaved(response) {
        if (response.success) {
            this.layer.msg('配置保存成功', {icon: 1});
            this.loadAvailableConfigs(); // 刷新配置列表
        } else {
            this.layer.msg('配置保存失败：' + response.msg, {icon: 2});
        }
    }

    /**
     * 处理配置加载成功回调
     */
    handleConfigLoaded(response) {
        if (response.success) {
            this.applyLoadedConfig(response.data);
            // this.renderConfigList(); // 更新按钮状态
        } else {
            this.layer.msg('配置加载失败：' + response.msg, {icon: 2});
        }
    }

    /**
     * 处理配置删除成功回调
     */
    handleConfigDeleted(response) {
        if (response.success) {
            this.layer.msg('配置删除成功', {icon: 1});
            this.loadAvailableConfigs(); // 刷新配置列表
        } else {
            this.layer.msg('配置删除失败：' + response.msg, {icon: 2});
        }
    }

}

// 创建全局DrawerManager实例
window.DrawerManager = new DrawerManager();


